package com.dragon.modules.yuegou.client.wechat.client.impl;

import com.dragon.modules.yuegou.client.wechat.client.WxApiV3Client;
import com.dragon.modules.yuegou.client.wechat.properties.WxApiV3Properties;
import com.dragon.modules.yuegou.client.wechat.request.PointsNotifyRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;

public class WxApiV3ClientImpl implements WxApiV3Client {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	private WebClient client = WebClient.create("https://api.mch.weixin.qq.com");

	private static final String pointsNotifyUri = "/v3/businesscircle/points/notify";

	private ObjectMapper objectMapper;

	private WxApiV3Properties properties;

	public WxApiV3ClientImpl(WxApiV3Properties properties) {
		this.properties = properties;
		objectMapper = new ObjectMapper();
		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	}

	@Override
	public void pointsNotify(PointsNotifyRequest request) {
		try {
			String result = client.post().uri(pointsNotifyUri).header("Content-Type", "application/json")
					.header("Authorization", getToken("POST", pointsNotifyUri, request)).syncBody(request)
					.accept(MediaType.APPLICATION_JSON).exchange().flatMap(res -> res.bodyToMono(String.class)).block();
			logger.info("微信APIV3接口[{}]请求返回{}", pointsNotifyUri, result);
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	private String getToken(String method, String url, Object request) {
		try {
			return WxAPIV3SignUtils.getToken(method, url, objectMapper.writeValueAsString(request),
					properties.getMchid(), properties.getSerialNo(), properties.getKeypem());
		} catch (JsonProcessingException e) {
			logger.error("", e);
		}
		return null;
	}
}
